package com.common.core.results;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.common.core.exception.code.BaseErrorCode;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author zhangwj
 * @date 2021/7/26 下午3:33
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class MultiResult<T> extends Result implements Serializable {

    private static final long serialVersionUID = 1L;

    MultiResult() {
    }

    @JSONField(ordinal = 5)
    private Multi<T> payload;

    public static <T> MultiResult<T> of() {
        Multi<T> multi = new Multi<>();
        return Result.multiResult(multi);
    }

    public static <T> MultiResult<T> of(Collection<T> data) {
        Multi<T> multi = new Multi<>();
        multi.setArray(data);
        return Result.multiResult(multi);
    }

    public static <T> MultiResult<T> failed(int errNum, String errMsg) {
        MultiResult<T> response = new MultiResult<>();
        response.setSuccess(false);
        response.setErrNum(errNum);
        response.setErrMsg(errMsg);
        return response;
    }

    public static <T> MultiResult<T> failed(BaseErrorCode errorCode) {
        MultiResult<T> response = new MultiResult<>();
        response.setSuccess(false);
        response.setErrNum(errorCode.getErrNum());
        response.setErrMsg(errorCode.getErrMsg());
        return response;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this, SerializerFeature.WriteMapNullValue);
    }

    @Data
    public static class Multi<T> {

        @JSONField(ordinal = 1)
        private Collection<T> array;

        public List<T> getArray() {
            if (null == array) {
                return Collections.emptyList();
            }
            return new ArrayList<>(array);
        }

        @JSONField(name = "isEmpty", ordinal = 2)
        public boolean isEmpty() {
            return CollectionUtils.isEmpty(this.array);
        }
    }
}
